﻿module Sustainalytics.Charts {

    export class SerialChartBehavior {

        constructor(
            private scope: SerialChartScope,
            private $timeout: ng.ITimeoutService,
            private element,
            private attrs) {

            var ctx = this;

            ctx.init();
        }

        // init logic
        private init(): void {
            var ctx = this;

            ctx.scope.isLoading = true;

            // when the data source changes then create chart
            (<ng.IScope><any>ctx.scope).$watch('userOptions', function () {

                // create AmSerialChart
                if (ctx.scope.userOptions && ctx.scope.userOptions.dataProvider) {
                    ctx.createAmChart();
                }
            });
        }

        // create AmSerialChart
        private createAmChart(): void {
            var ctx = this;

            // show that is loading
            ctx.$timeout(function () {
                ctx.scope.isLoading = true;
            });

            // create default options
            var defaultOptions = ctx.createDefaultOptions();

            // create options by extending default options with user options
            var options = $.extend(true, defaultOptions, ctx.scope.userOptions);

            AmCharts['makeChart'](ctx.element.attr('id'), options);

            // show that was loaded
            ctx.$timeout(function () {
                ctx.scope.isLoading = false;
            });
        }

        private createDefaultOptions(): any {
            var defaultOptions = {
                "type": "serial",
                "pathToImages": "//cdn.amcharts.com/lib/3/images/",
            };

            return defaultOptions;
        }
    }


    angular.module(chartsModuleName).directive('sustainalyticsChartSerial', function ($timeout) {

        return {
            // apply by class
            restrict: 'C',

            // generate child scope
            scope: {
                userOptions: '=useroptions',
                isLoading: '=isloading'
            },

            // associate with controller
            controller: 'SerialChartController',

            // link function for attaching event handlers and applying scope
            link: function (scope: SerialChartScope, element, attrs) {
                var behavior = new SerialChartBehavior(scope, $timeout, element, attrs);
            }
        };
    })
}